<?php


namespace app\middleware;

use app\back\model\AdminModel;
use think\facade\Cache;
use think\facade\Db;
use app\Request;
use \Closure;
use \Exception;
/**后台校验请求
 * Class BackAuth
 * @package app\middleware
 */
class BackAuth
{
    private $filter = [
        'login',
        'logout',
        'test',
        'admin_list',
        'sort_center_list',
        'category_all',
        'category_product',
        'category_children',
        'category_one',
        'UpdateBalance',
    ]; // 跳过校验

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            header('Content-Type: text/html;charset=utf-8');
            header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
//        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
            header('Access-Control-Allow-Methods:POST,GET'); // 允许请求的类型
            header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
            header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin,Authorization'); // 设置允许自定义请求头的字段
            // 校验请求方式
            if (!$request->isPost()) return jsonFail('不允许的请求方式');

            if (!in_array($request->action(), $this->filter)) {
                // 校验参数签名
                if (checkSign($request->post()) == false) return jsonFail('参数验签失败');
                // 校验token
                $token = $request->header('authorization');
                if ($token == null) return jsonFail('登录态失效，请重新登录');
                $info = Cache::store('redis')->handler()->get($token);
                if (!$info) return jsonFail('登录态失败,请重新登录');
                // 验证权限
                $infos = explode('-', $info);
                if ($infos['0'] !== 'admin') return jsonFail('验证类型不一致');
                $adminId =$infos[1];
                if ($request->action() == 'getMenus') {
                    $request->info = ['id' => $adminId];
                } else {
                    $info = AdminModel::checkAuth($adminId, $request->url());
                    if (!is_array($info)) return $info;
                    $request->info = $info;
                    $response = $next($request);
                    // 记录日志
                    $postData = $request->post();
                    unset($postData['nonceStr']);
                    unset($postData['sign']);
                    $responseData = $response->getData();
                    $logData = [
                        'admin_id' => $info['id'],
                        'admin_name' => $info['name'],
                        'path' => $request->query(),
                        'param' => json_encode($postData),
                        'result' => isset($responseData['msg']) ? $responseData['msg'] : '未知错误',
                        'ip' => $request->ip(),
                        'add_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('eb_system_log')->insert($logData);
                    return $response;
                }
            }
            $response = $next($request);
            return $response;
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

////    /**进行额外操作
////     * @param Response $response
////     */
//    public function end(Response $response)
//    {
//
//    }
}